const app = getApp();
Page({
  data: {
    interval: 2200, //自动切换时间间隔
    autoplay: true,
    duration: 500, //滑动动画时长
    circular: true, //衔接滑动
    indicatorDots: false, //标记



    hidden: false, //加载
    outline: false, //有无网络
    imgUrls: [],//轮播
    list: [],//页面数据
    deviceid: 'M2019000860', //设备号
    phone: '',
    status1: 1,
    type: 1,

    openid: '',
    add: false,
    kind: 0,
    token: '',
    issaoma: false,

    userId: '',
    name: '',
    number: '',
    price: '',
    address: '',

    message: ''//第二次半价
  },
  add: function() {
    var that = this;
    that.get();
    that.setData({
      add: true
    })
  },
  cancel: function() {
    var that = this;
    that.setData({
      add: false
    })
  },
  click: function(e) {
    var that = this;

    that.setData({
      kind: e.currentTarget.dataset.id,
      name: '',
      number: '',
      price: '',
      address: ''
    })
  },
  onLoad(query) {
  },
  phone() {
    my.makePhoneCall({ number: this.data.phone });
  },


  name: function(e) {
    var that = this;
    that.setData({
      name: e.detail.value
    })
  },
  number: function(e) {
    var that = this;
    that.setData({
      number: e.detail.value
    })
  },
  price: function(e) {
    var that = this;
    that.setData({
      price: e.detail.value
    })
  },

  name1: function(e) {
    var that = this;
    that.setData({
      name: e.detail.value
    })
  },
  phone1: function(e) {
    var that = this;
    that.setData({
      number: e.detail.value
    })
  },
  address: function(e) {
    var that = this;
    that.setData({
      address: e.detail.value
    })
  },
  sub: function() {
    var that = this;
    // 校验电话
    var mobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    var isMobile = mobile.exec(that.data.number)
    if (that.data.name == '' || that.data.number == '') {
      my.showToast({
        content: '请完整填写信息',
        icon: 'none',
        duration: 1500
      })
      return
    } else if (!isMobile) {
      my.showToast({
        content: '你输入的电话不符，请重新检查填写',
      })
      return
    }
    if (that.data.kind == 0) {
      if (that.data.price == '') {
        my.showToast({
          content: '请完整填写信息',
          icon: 'none',
          duration: 1500
        })
        return
      }
      that.submit()
    } else {
      if (that.data.address == '') {
        my.showToast({
          content: '请完整填写信息',
          icon: 'none',
          duration: 1500
        })
        return
      }
      that.submit()
    }
  },
  submit() {
    var that = this;
    var req = {
      type: that.data.kind,
      username: that.data.name,
      phone: that.data.number,
      address: that.data.address,
      money: that.data.price,
      userId: that.data.userId
    }
    that.setData({
      hidden: true
    })
    my.request({
      url: 'https://www.tiantong369.com/crm/feedback',
      data: req,
      method: "POST",
      //头信息设置
      header: {},
      success: function(res) {
        that.setData({
          hidden: false
        })
        if (res.data.status == 200) {
          that.setData({
            add: false
          })
          my.showToast({
            content: res.data.message,
            icon: 'none',
            duration: 1500
          })
        }
      },
      fail: function(res) {

      }
    });
  },




  onReady() {

  },
  onShow() {
    var that = this;
    my.getNetworkType({
      success: (res) => {
        if (res.networkAvailable) {
          that.setData({
            outline: false,
            type: 1,
          })
          if (app.issaoma == true) {
            that.setData({
              issaoma: true,
              deviceid: app.deviceid
            })

          } else {
            that.setData({
              issaoma: false,
              deviceid: that.data.deviceid
            })
          }
          that.getToken();
        } else {
          that.setData({
            outline: true
          })
        }
      }
    })
  },

  get() {
    var that = this;
    my.getAuthCode({
      scopes: 'auth_user',
      success: (res) => { //获取用户信息
        my.getAuthUserInfo({
          success: (res) => {
            var req = {
              openid: that.data.openid,
              nickname: res.nickName,
              headimgurl: res.avatar,
              sex: '',
              province: '',
              city: '',
            }
            my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
              url: 'https://www.tiantong369.com/crm/myuserinfo', // 该url是自己的服务地址
              method: 'POST',
              data: req,
              headers: {
                'x-access-token': that.data.token
              },
              success: (res) => {// 成功获取订单号
                if (res.data.status == 200) {
                  that.setData({
                    imgUrl: res.data.data.headimgurl,
                    nickName: res.data.data.nickname,
                    userId: res.data.data.id,
                    login: 1
                  })
                  my.setStorageSync(
                    {
                      key: "imgUrl",
                      data: res.data.data.headimgurl
                    }
                  );
                  my.setStorageSync(
                    {
                      key: "nickName",
                      data: res.data.data.nickname
                    }
                  );
                  my.setStorageSync(
                    {
                      key: "userId",
                      data: res.data.data.id
                    }
                  );

                } else {
                  my.showToast({
                    content: '' + res.data.message + '',
                  })
                }
              },
              fail: (res) => {
                console.log('/Wxpay_callback:', res)
              },
            });
          },
        });

      },
    })
  },
  // 扫码
  scan() {
    my.scan({
      type: 'qr',
      success: (res) => {
        var str = JSON.stringify(res.code)
        this.setData({
          deviceid: str.substring(str.length - 12, str.length - 1),
          issaoma: true
        })
        app.issaoma = true;
        my.setStorage({
          key: 'deviceid',
          data: str.substring(str.length - 12, str.length - 1),
        })
      },
    });
  },

  radioChange: function(e) {
    var that = this;
    var items = that.data.list;
    for (var i = 0; i < items.length; i++) {
      if (e.detail.value == i) {
        items[i].checked = true;
      } else {
        items[i].checked = false;
      }
    }
    that.setData({
      type: e.detail.value,
      list: items
    })
  },
  // 获取token
  getToken() {
    var that = this;
    my.getAuthCode({
      scopes: 'auth_user', //授权类型，默认auth_base(静默授权)，支持auth_base/auth_user(主动授权)
      success: (res) => {
        if (res.authCode) { // 认证成功
          my.request({ // 成功之后调用后台开启设备接口
            url: 'https://www.tiantong369.com/gettoken',
            method: 'POST',
            data: { code: res.authCode },
            success: (res) => {
              if (res.status == 200) {
                my.setStorageSync({ key: 'token', data: '' + res.data.token + '' })
                that.getOpenid()
                that.getLunbo()
                that.post()
              }
            },
            fail: (res) => {
              console.log('fail:', res)
            },
          });
        }
      },
    })
  },
  //获取openid
  getOpenid: function() {
    var that = this;
    my.getAuthCode({ // 获取用户code
      scopes: 'auth_user', // 主动授权（弹框）：auth_user，静默授权（不弹框）：auth_base
      success: (res) => {
        if (res.authCode) { // 认证成功
          var req = {
            code: res.authCode
          }
          my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
            url: 'https://www.tiantong369.com/crm/getalipayuser/', // 该url是自己的服务地址
            method: 'POST',
            data: req,
            headers: {
              // 'x-access-token': this.data.token
            },
            success: (res) => {//
              if (res.status == 200) {
                that.setData({
                  openid: res.data.userId
                })

                my.setStorage({
                  key: 'openid', // 缓存数据的key
                  data: res.data.userId, // 要缓存的数据
                });
                that.post()
              }
            },
            fail: (res) => {
              console.log('fail:', res)
            },
          });
        }
      },
    });

  },

  //获取页面轮播信息
  getLunbo: function() {
    var that = this;
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/index/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: {},
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        if (res.data.status == 200) {
          console.log('***+', res.data.app.banner)
          that.setData({
            phone: res.data.app.phone,
            imgUrls: res.data.app.banner,
            success: res.data.app.success
          })
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    });
  },
  //获取页面列表信息
  post: function() {
    var that = this;
    var req = {
      deviceid: that.data.deviceid, openid: that.data.openid
    }
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/GetEmpPrice', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: req,
      dataType: 'json',
      success: (res) => {
        that.setData({
          hidden: false
        })
        if (res.data.status == 200) {
          var arr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            arr.push(res.data.data[i])
          }
          arr[1].checked = true

          that.setData({
            list: arr,
            message: res.data.data[0].message
          })
          console.log('message', that.data.message)
        } else {
          my.showToast({
            content: res.data.err_msg
          })
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    });
  },
  // 点击付款
  powerDrawer() {
    var that = this;
    that.get();
    if (that.data.issaoma == false) {
      my.alert({ content: '未检测到设备，请点击右上角的扫一扫，选择正确的二维码扫描...' });
      return;
    }
    that.setData({
      status1: 1,
      hidden: true

    })
    var obj = { deviceid: that.data.deviceid }
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/senddevicemsg/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: obj,
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        if (res.data.status == 200) {
          that.startSetInter()
        } else {
          my.showToast({ content: res.data.err_msg });
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    })
  },
  startSetInter: function() {
    var that = this;
    var obj = { deviceid: that.data.deviceid, openid: that.data.openid }
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/GetEmpPrice/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: obj,
      dataType: 'json',
      success: (res) => {
        if (res.data.device.status == 1) {
          that.pay();
        } else {
          that.data.status1++
          if (that.data.status1 < 20) {
            setTimeout(function() {
              that.startSetInter();
            }, 1500)
          } else {
            that.setData({
              hidden: false
            })
            my.alert({ content: '设备正在联网，请5秒后扫码重试...' });
            return;
          }
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    })

  },
  pay: function() {
    var that = this;
    my.getAuthCode({ // 获取用户code
      scopes: 'auth_user', // 主动授权（弹框）：auth_user，静默授权（不弹框）：auth_base
      success: (res) => {
        if (res.authCode) { // 认证成功
          var req = {
            ucode: res.authCode,
            from: '摩倍',
            goods: '足疗按摩',
            money: that.data.list[that.data.type].price,
            time: that.data.list[that.data.type].second,
            deviceid: that.data.deviceid,
          }
          my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
            url: 'https://www.tiantong369.com/crm/alipay_createorder/', // 该url是自己的服务地址
            method: 'POST',
            data: req,
            headers: {
              'x-access-token': this.data.token
            },
            success: (res) => {//
              this.setData({ hidden: false })
              if (res.data.status == 200) {
                var that = this;
                my.tradePay({// 调用此方法唤起支付宝收银台item
                  tradeNO: res.data.data.tradeNo,
                  success: function(res) {
                    if (res.resultCode != '6001') { // 付款成功
                      my.alert({ content: '' + that.data.success + '' });

                    } else { // 用户点了×，并未付款
                      my.alert({ content: '付款失败' });
                    }
                  },
                  fail: function(res) {
                    // console.log('fail', res)
                  },
                });
              }


            },
            fail: (res) => {
              console.log('fail:', res)
            },
          });
        }
      },
    });
  },

  goodsDetail: function(e) {
    console.log(e)
    my.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodid=' + e.target.dataset.id
    })
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {

  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },



















});
